import { Injectable } from '@nestjs/common';
import CreateDto from './dto/create.dto';
import { DbService } from 'apps/admin/src/db/db.service';
import WorkException from 'exception/work.exception';
import UpdateDto from './dto/update.dto';
import { SysConfig } from '@app/db/common/entity/SysConfig';

@Injectable()
export class SysConfigService {
    constructor(
        private readonly db:DbService
    ){}

    config() {
        return this.db.sysConfig.selectValues('STATIC_URL')
    }

    list() {
        return this.db.sysConfig.find(null, null, null, null, {id : 'DESC'})
    }

    async add(dto:CreateDto) {
        if((await this.db.sysConfig.isExistsByWhere({name : dto.name}))) throw new WorkException('已存在相同的名称')
        if((await this.db.sysConfig.isExistsByWhere({code : dto.code}))) throw new WorkException('已存在相同的编码')

        const r = await this.db.sysConfig.insert(dto)

        return r
    }

    async update(dto:UpdateDto) {
        const row = await this.db.sysConfig.findOne({id : dto.id})
        if(!row) return false
        let updateData:KeyToValueType<SysConfig> = {}

        if(dto.name != undefined) {
            if(row.name != dto.name) {
                updateData.name = dto.name
            }
        }

        if(dto.code != undefined) {
            if(row.code.toLocaleLowerCase() != dto.code.toLocaleLowerCase()) {
                updateData.code = dto.code
            }
        }

        if(dto.config != undefined) {
            updateData.config = dto.config
        }

        if((Object.keys(updateData)).length == 0) return true

        if(updateData.name && (await this.db.sysConfig.isExistsByWhere({name : dto.name}))) throw new Error('已存在相同的名称')
        if(updateData.code && (await this.db.sysConfig.isExistsByWhere({code : dto.code}))) throw new Error('已存在相同的编码')

        return this.db.sysConfig.update({id : dto.id}, dto)
    }

    async updateItem(id:number, dto:{[key:string] : any}) {
        const row = await this.db.sysConfig.findOne({id : id})
        if(!row) return false
        for(let k in dto) {
            row.config[k].value = dto[k]
        }


        return this.db.sysConfig.update({id : id}, {config : row.config})
    }

    async del(id:number) {
        let row = await this.db.sysConfig.findOne({ id })
        if(!row) return
        return this.db.sysConfig.delete({id : id})
    }
}
